package handlers

import (
	"down-man-sys/cache"
	"down-man-sys/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	comment := c.PostForm("comment")
	xiaCount, _ := strconv.Atoi(c.PostForm("xiaCount"))
	types := c.PostForm("type")
	if name == "" || comment == "" || xiaCount < 0 || types == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := model.Shop{
		Name:     name,
		Comment:  comment,
		XiaCount: xiaCount,
		Type:     types,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg": "添加成功" +
				"" +
				"",
		})
		return
	}
}
func List(c *gin.Context) {
	var shop []model.Shop

	redis_key := "list_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&shop)
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": shop,
	})

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var shop model.Shop
	model.DB.Where("id = ?", id).Find(&shop)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "查询成功",
		"data": shop,
	})
}
func Xia(c *gin.Context) {
	data := model.Shop{
		Name:     "",
		Comment:  "",
		XiaCount: 0,
		Type:     "",
	}
	data.XiaCount++
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "下载成功",
	})
	return
}
